package dsx.converter;

import com.fasterxml.jackson.databind.ObjectMapper;

import dsx.console.DsxConsole;
import dsx.inf.IConverter;
import dsx.log.ServLog;

public class Converter_json implements IConverter {
	
	static ObjectMapper mapper = new ObjectMapper();
	
	final String encoding = "UTF-8";
	
	@Override
	public byte[] toBytes(Object obj) {
		try {
			String json = mapper.writeValueAsString(obj);
			DsxConsole.out(json, "biz", ServLog.info);
			byte[] jsonBytes = json.getBytes(encoding);
			byte[] answBytes = new byte[jsonBytes.length + 1];
			System.arraycopy(jsonBytes, 0, answBytes, 0, jsonBytes.length);
			answBytes[answBytes.length - 1] = 0;
			return answBytes;
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public Object toObject(byte[] data, Class<?> classType) {
		try {
			String json = new String(data, encoding);
			return mapper.readValue(json, classType);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public String toString(Object obj) {
		try {
			String json = mapper.writeValueAsString(obj);
			return json;
		} catch (Exception ex) {
			return null;
		}
	}
	
	@Override
	public Object toObject(String json, Class<?> classType) {
		try {
			return mapper.readValue(json, classType);
		} catch (Exception ex) {
			DsxConsole.out(ex.getMessage(), "converter_json", ServLog.error);
			return null;
		}
	}
	
}
